package view;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.SearchSpecifications;
import model.SearchSpecifications.SearchCategory;
import model.Work;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/Search")
public class SearchServlet extends Servlet {
	private static final long serialVersionUID = 1L;

	private List<Work> searchBy(String searchString, SearchSpecifications specifications) throws Exception {
		return new Work().loadWorks(searchString, specifications);
	}

	@Override
	void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		printSearchForm(out, SearchCategory.Título, "");
	}

	private void printSearchForm(PrintWriter out, SearchCategory sCategory, String searchString) {
		/* @formatter:off */
		out.println("<form id='searchForm' action='Controller' method='POST'>");
		out.println("	<label for='searchCategory'>Buscar por:</label>");
		out.println(	HtmlFactory.createCategoryCombo(sCategory));
		out.println("	<input type='text' name='searchInput' size='50' value='"+searchString+"'>");
		out.println("	<input type='submit' name='button' value='Pesquisar'>");
		out.println("</form>");
		/* @formatter:on */
	}

	@Override
	void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		String searchString = request.getParameter("searchInput");

		try {
			SearchSpecifications ss = new SearchSpecifications(20, 1, parseSearchCategory(request));
			printSearchForm(out, ss.getCategory(), searchString);

			for (Work work : searchBy(searchString, ss)) {
				printWork(out, work);
			}
		} catch (Exception ex) {
			out.println(HtmlFactory.createErrorMessage(ex.getMessage()));
			printSearchForm(out, SearchCategory.Título, "");
			ex.printStackTrace();
		}
	}

	private void printWork(PrintWriter out, Work work) {
		out.println("<form class='workIntro' id='work" + work.getId() + "' action='Controller' method='GET'>");
		out.println("	<input type='hidden' name='workId' value='" + work.getId() + "'>");
		out.println("	<div class='title'>" + work.getTitle() + "</div></br>");
		out.println("	<div class='theme'> Tema: " + work.getTheme() + "</div></br>");
		out.println("	<div class='category'> Categoria: " + work.getCategory().toString() + "</div></br>");
		out.println("	<div class='authorName'> Autor: " + work.getAuthorName() + "</div></br>");
		out.println("	<input type='submit' name='button' value='Download'>");
		out.println("</form>");
	}

	private SearchCategory parseSearchCategory(HttpServletRequest request) throws Exception {
		try {
			return SearchCategory.values()[Integer.valueOf(request.getParameter("searchCategory"))];
		} catch (IndexOutOfBoundsException ex) {
			throw new Exception("Esta categoria de busca não existe!");
		}
	}
}
